package com.chongba.schedule.jdk;

import java.util.Calendar;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class DelayedTask implements Delayed {

    //任务的执行时间
    private int executeTime = 0;

    public DelayedTask(int delay){
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.SECOND, delay);
        this.executeTime = (int)(calendar.getTimeInMillis()/1000);
    }

    @Override
    public long getDelay(TimeUnit unit) {
        int delay = executeTime - (int) (System.currentTimeMillis() / 1000);
        return delay;
    }

    @Override
    public int compareTo(Delayed o) {
        long l = this.getDelay(TimeUnit.NANOSECONDS) - o.getDelay(TimeUnit.NANOSECONDS);
        return l == 0?0:(l<0 ? -1 : 1);
    }

    public static void main(String[] args) {
        DelayQueue<DelayedTask> queue = new DelayQueue<>();

        queue.add(new DelayedTask(5));
        queue.add(new DelayedTask(10));
        queue.add(new DelayedTask(15));

        System.out.println(System.currentTimeMillis()/1000+"cosume task");
        while (queue.size()!=0){
            DelayedTask delayedTask = queue.poll();
            if (delayedTask != null){
                System.out.println(System.currentTimeMillis()/1000+"cosume task");
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
